package jobhunter.repository;

import java.util.List;

import jobhunter.model.Company;
import jobhunter.model.Contact;
import jobhunter.security.SecurityContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@SuppressWarnings("unchecked")
public class ContactRepository extends GenericRepositoryJpa<Contact> 
{

	public ContactRepository() {
		setEntityClass(Contact.class);
	}
	public List<Contact> findByCompany(Company company)
	{
		return (List<Contact>) em.createQuery("SELECT c FROM Contact c WHERE c.company=:company AND c.user=:user ORDER BY c.id DESC")
				.setParameter("company", company).setParameter("user", SecurityContext.getUser()).getResultList();
	}


	public Contact findByIdWithActions(Long id)
	{
		return (Contact)em.createQuery("SELECT c FROM Contact c LEFT JOIN FETCH c.actions Where c.id = :id AND c.user=:user")
				.setParameter("id", id).setParameter("user", SecurityContext.getUser()).getSingleResult();
		
	}
	

	
	@Override
	public Contact merge(Contact t) {
		if(t.getUser()==SecurityContext.getUser())
			return em.merge(t);
		else
			return null;
	}
	@Override
	public void remove(Contact t) 
	{
		if(t.getUser()==SecurityContext.getUser())
			em.remove(t);		
	}
}
